<script setup>
import { useUserStore } from '@/stores/user';
import { getLikeListAPI, getAddressAPI,setDefaultAPI } from '@/api/user'
import { onMounted, ref } from 'vue';
import GoodsItem from '@/views/home/components/GoodsItem.vue'
import { getAreaAPI, addAreaAPI, delAreaAPI } from '@/api/checkout';
const userStore = useUserStore()
const likeList = ref([])
const getLikeList = async () => {
  const { result } = await getLikeListAPI({ limit: 4 })
  likeList.value = result
}
onMounted(() => {
  getLikeList()
  getAddress()
})

//添加地址    
const userAddress = ref([])
const getAddress = async () => {
  const { result } = await getAddressAPI()
  userAddress.value = result
}
const toggleFlag = ref(false)
const addFlag = ref(false)
const ruleForm = ref({
  id: '',
  receiver: '',
  phone: '',
  address: '',
  fullLocation: [],
  addressTags: []
})
const ruleFormRef = ref(null)
const rule = {
  receiver: [
    { required: true, message: '请输入收货人', trigger: 'trigger' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'trigger' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'trigger' },
    { min: 11, max: 11, message: '长度在 11 个字符', trigger: 'trigger' }
  ],
  address: [
    { required: true, message: '请输入收货地址', trigger: 'trigger' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'trigger' }
  ],
  fullLocation: { required: true, message: '请选择收货地址', trigger: 'trigger' }
}
const areaProps = {
  lazy: true, // 开启懒加载
  lazyLoad: async (node, resolve) => {
    const { level, value } = node;
    let keywords = null;
    if (level > 0) {
      // 如果不是顶级节点，将上一级的 value 作为 keywords
      keywords = value;
    }
    try {
      // 调用后端接口获取行政区域数据
      const response = await getAreaAPI(keywords);
      const districts = response.result;
      console.log(districts);
      const nodes = districts.map((district) => ({
        value: district.name, // 使用区域名称作为 value
        label: district.name, // 使用区域名称作为 label
        leaf: district.districts.length === 0 // 判断是否为叶子节点
      }));
      // 调用 resolve 回调返回子节点数据
      resolve(nodes);
    } catch (error) {
      console.error('获取行政区域数据失败:', error);
      resolve([]);
    }
  }
};
const handleClose = () => {
  addFlag.value = false
  updateFlag.value = false
  ruleForm.value = {
    id: '',
    receiver: '',
    phone: '',
    address: '',
    fullLocation: [],
    addressTags: []
  }
  toggleFlag.value = true
}
const submit = (i) => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      const submitFrom = { ...ruleForm.value, fullLocation: ruleForm.value.fullLocation.join(' '), addressTags: ruleForm.value.addressTags.join(' ') }
      await addAreaAPI(submitFrom)
      if (i === 1)
        ElMessage.success('插入成功')
      else
        ElMessage.success('更新成功')
      handleClose()
      getAddress()
      toggleFlag.value = true

    } else {
      console.log('error submit!');
    }
  })
}

const updateFlag = ref(false)
const handleEdit = async (item) => {
  toggleFlag.value = false
  ruleForm.value = { ...item, fullLocation: item.fullLocation.split(' '), addressTags: item.addressTags.split(' ') }
  updateFlag.value = true
}

const handleDelete = async (id) => {
  await delAreaAPI(id).then (() => {
    ElMessage.success('删除成功')
  })
  getAddress()
  toggleFlag.value = true
}
const handleAdd = () => {
  addFlag.value = true
  toggleFlag.value = false
}
const setDefault = async (id) => {
  await setDefaultAPI(id).then(() => {
    ElMessage.success('设置成功')
  })
  getAddress()
}
</script>

<template>
  <div v-if="addFlag" class="overlay"></div>
  <div class="home-overview">
    <!-- 用户信息 -->
    <div class="user-meta">
      <div class="avatar">
        <img :src="userStore.userInfo?.avatar" />
      </div>
      <h4>{{ userStore.userInfo?.account }}</h4>
    </div>
    <div class="item">
      <a href="javascript:;">
        <span class="iconfont icon-hy"></span>
        <p>会员中心</p>
      </a>
      <a href="javascript:;">
        <span class="iconfont icon-aq"></span>
        <p>安全设置</p>
      </a>
      <a href="javascript:;" @click="toggleFlag = true">
        <span class="iconfont icon-dw"></span>
        <p>地址管理</p>
      </a>
    </div>
  </div>
  <div class="like-container">
    <div class="home-panel">
      <div class="header">
        <h4 data-v-bcb266e0="">猜你喜欢</h4>
      </div>
      <div class="goods-list">
        <GoodsItem v-for="good in likeList" :key="good.id" :good="good" />
      </div>
    </div>
  </div>

  <!-- 地址管理 -->
  <el-dialog title="地址管理" width="30%" center v-model="toggleFlag" style="z-index: 1000;">
    <div class="addressWrapper">
      <div class="text item " v-for="item in userAddress" :key="item.id">
        <ul>
          <li><span>收<i />货<i />人：</span>{{ item.receiver }} 
          <span v-if="item.isDefault===0"  style="color: darkorange; font-size: 14px; margin-left: 150px">默认</span>
          </li>
          <li><span>联系方式：</span>{{ item.phone }}</li>
          <li><span>收货地址：</span>{{ item.fullLocation + item.address }}</li>
          <li><span class="edit" @click="handleEdit(item)">编辑</span><span class="edit"
              @click="handleDelete(item.id)">删除</span> <span class="edit" v-if="item.isDefault===1" @click="setDefault(item.id)">设为默认</span></li>
        </ul>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleAdd()">新增</el-button>
        <el-button type="primary" @click="toggleFlag = false">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 添加地址 -->
  <div v-if="addFlag" class="add-box">
    <div class="add-box-header">
      <span class="add-box-title">添加地址</span>
      <span class="close-icon" @click="handleClose()">×</span>
    </div>
    <el-form label-position="right" label-width="100px" :rules="rule" ref="ruleFormRef" :model="ruleForm" status-icon>
      <el-form-item label="地址" prop="fullLocation">
        <el-cascader class="inp" v-model="ruleForm.fullLocation" :props="areaProps" placeholder="请选择地址"
          style="margin-left: 5%; width: 70%;" clearable />
      </el-form-item>
      <el-form-item label="收货人" prop="receiver">
        <el-input class="inp" v-model="ruleForm.receiver"></el-input>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input class="inp" v-model="ruleForm.address"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input class="inp" v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="标签" prop="addressTags">
        <el-input-tag class="inp" v-model="ruleForm.addressTags" placeholder="Please click the Enter key after input" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit(1)" style="margin-top: 20px;">提交</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 修改地址 -->
  <div v-if="updateFlag" class="add-box">
    <div class="add-box-header">
      <span class="add-box-title">添加地址</span>
      <span class="close-icon" @click="handleClose()">×</span>
    </div>
    <el-form label-position="right" label-width="100px" :rules="rule" ref="ruleFormRef" :model="ruleForm" status-icon>
      <el-form-item label="地址" prop="fullLocation">
        <el-cascader class="inp" v-model="ruleForm.fullLocation" :props="areaProps" placeholder="请选择地址"
          style="margin-left: 5%; width: 70%;" clearable />
      </el-form-item>
      <el-form-item label="收货人" prop="receiver">
        <el-input class="inp" v-model="ruleForm.receiver"></el-input>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input class="inp" v-model="ruleForm.address"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input class="inp" v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="标签" prop="addressTags">
        <el-input-tag class="inp" v-model="ruleForm.addressTags" placeholder="Please click the Enter key after input" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit(2)" style="margin-top: 20px;">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
.home-overview {
  height: 132px;
  background: url(@/assets/images/center-bg.png) no-repeat center / cover;
  display: flex;

  .user-meta {
    flex: 1;
    display: flex;
    align-items: center;

    .avatar {
      width: 85px;
      height: 85px;
      border-radius: 50%;
      overflow: hidden;
      margin-left: 60px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    h4 {
      padding-left: 26px;
      font-size: 18px;
      font-weight: normal;
      color: white;
    }
  }

  .item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-around;

    &:first-child {
      border-right: 1px solid #f4f4f4;
    }

    a {
      color: white;
      font-size: 16px;
      text-align: center;

      .iconfont {
        font-size: 32px;
      }

      p {
        line-height: 32px;
      }
    }
  }
}

.like-container {
  margin-top: 20px;
  border-radius: 4px;
  background-color: #fff;
}

.home-panel {
  background-color: #fff;
  padding: 0 20px;
  margin-top: 20px;
  height: 400px;

  .header {
    height: 66px;
    border-bottom: 1px solid #f5f5f5;
    padding: 18px 0;
    display: flex;
    justify-content: space-between;
    align-items: baseline;

    h4 {
      font-size: 22px;
      font-weight: 400;
    }

  }

  .goods-list {
    display: flex;
    justify-content: space-around;
  }
}

/* 遮罩层样式 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  /* 半透明黑色背景 */
  z-index: 999;
  /* 确保遮罩层在其他元素之上 */
}

.add-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
  width: 600px;
  height: 600px;
  z-index: 1001;

  .inp {
    width: 70%;
    margin-left: 5%;
  }

  .add-box-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5%;
    background-color: #f5f5f5;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
  }

  .add-box-title {
    margin: 0;
    font-size: 18px;
    font-weight: bold;
  }

  .close-icon {
    cursor: pointer;
    font-size: 20px;
    font-weight: bold;
  }

}

.addressWrapper {
  max-height: 500px;
  overflow-y: auto;
}

.edit {
  color: $xtxColor;
  margin-right: 10%;
  margin-left: 10%;

  &:hover {
    color: red;
  }
}

.text {
  flex: 1;
  min-height: 90px;
  display: flex;
  align-items: center;

  &.item {
    border: 1px solid #f5f5f5;
    margin-bottom: 10px;
    cursor: pointer;

    &.active,
    &:hover {
      border-color: $xtxColor;
      background: lighten($xtxColor, 50%);
    }

    >ul {
      padding: 10px;
      font-size: 14px;
      line-height: 30px;
    }
  }
}
</style>